package com.iwgang.familiarrecyclerviewdemo.slice;

import com.iwgang.familiarrecyclerview.FamiliarRefreshRecyclerView;
import com.iwgang.familiarrecyclerview.FamiliarWrapRecyclerViewAdapter;
import com.iwgang.familiarrecyclerviewdemo.ResourceTable;
import com.iwgang.familiarrecyclerviewdemo.util.ToastUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ImitateListViewDemoAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private FamiliarRefreshRecyclerView     mRecyclerView;
    private ArrayList<String>               mData;
    private MyAdapter                       mAdapter;
    private FamiliarWrapRecyclerViewAdapter mRecyclerViewAdapter;

    @Override
    protected void onStart(Intent intent) {
        try {
            int color = getResourceManager().getElement(ResourceTable.Color_title_bar_bg).getColor();
            getWindow().setStatusBarColor(color);
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_imitate_list);
        initView();
    }

    private void initView() {
        mData = new ArrayList<>();
        mData.addAll(getData());
        Component recycleView = findComponentById(ResourceTable.Id_cv_refreshListRecyclerView);
        if (recycleView instanceof FamiliarRefreshRecyclerView) {
            mRecyclerView = (FamiliarRefreshRecyclerView) recycleView;
        }
        ListContainer listContainer = new ListContainer(this);
        listContainer.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
        listContainer.setHeight(ComponentContainer.LayoutConfig.MATCH_CONTENT);
        mAdapter = new MyAdapter();
        mRecyclerViewAdapter = new FamiliarWrapRecyclerViewAdapter(mAdapter);

        // add headView
        addHeadView();

        // set EmptyView
        setEmptyView();
        listContainer.setItemProvider(mRecyclerViewAdapter);

        // 因为ListContainer自带拖拽功能,这里屏蔽掉该功能才能禁止拖拽功能
        listContainer.setLongClickable(false);
        mRecyclerView.setDataSizes(mRecyclerViewAdapter.getCount());
        mRecyclerView.addContentView(listContainer);

        setListener();
        Component add = findComponentById(ResourceTable.Id_tv_add);
        if (add instanceof Text) {
            Text tvAdd = (Text) add;
            tvAdd.setClickedListener(this);
        }
        Component delete = findComponentById(ResourceTable.Id_tv_delete);
        if (delete instanceof Text) {
            Text tvDelete = (Text) delete;
            tvDelete.setClickedListener(this);
        }
    }

    private void setListener() {
        // 下拉刷新回调
        mRecyclerView.setOnPullRefreshListener(() ->
                new EventHandler(EventRunner.getMainEventRunner()).postTask(() -> {
                    mData.clear();
                    mData.addAll(getData());
                    mAdapter.notifyDataChanged();
                    mRecyclerViewAdapter.notifyDataChanged();
                    mRecyclerView.setDataSizes(mRecyclerViewAdapter.getCount());
                }, 1000));

        // 上拉加载回调
        mRecyclerView.setOnLoadMoreListener(() ->
                new EventHandler(EventRunner.getMainEventRunner()).postTask(() -> {
                    int curMaxData = mData.size();
                    for (int i = 0; i < 30; i++) {
                        mData.add("item : " + (curMaxData + i));
                    }
                    mAdapter.notifyDataChanged();
                    mRecyclerViewAdapter.notifyDataChanged();
                    mRecyclerView.setDataSizes(mRecyclerViewAdapter.getCount());
                }, 1000));

        mRecyclerViewAdapter.setOnItemClickListener((component, position) -> {
            if (position != 0) {
                ToastUtil.makeText(getContext(),
                        "onItemClick = " + position, LayoutAlignment.BOTTOM);
            }
        });

        mRecyclerViewAdapter.setOnItemLongClickListener((component, position) -> {
            if (position != 0) {
                ToastUtil.makeText(getContext(),
                        "onItemLongClick = " + position, LayoutAlignment.BOTTOM);
            }
        });
    }

    private void setEmptyView() {
        LayoutScatter mLayoutScatter2 = LayoutScatter.getInstance(this);
        mRecyclerViewAdapter.setEmptyView(mLayoutScatter2
                .parse(ResourceTable.Layout_empty_view, null, false));
    }

    private void addHeadView() {
        LayoutScatter mLayoutScatter = LayoutScatter.getInstance(this);
        mRecyclerViewAdapter.addHeaderView(mLayoutScatter
                .parse(ResourceTable.Layout_view_header_ver, null, false));
    }

    private List<String> getData() {
        List<String> tempData = new ArrayList<>();
        int curMaxData = mData.size();
        for (int i = 0; i < 30; i++) {
            tempData.add("item:" + (curMaxData + i));
        }
        return tempData;
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_tv_add:
                mData.add("new add item:" + mData.size());
                mAdapter.notifyDataChanged();
                mRecyclerViewAdapter.notifyDataChanged();
                mRecyclerView.setDataSizes(mRecyclerViewAdapter.getCount());
                break;
            case ResourceTable.Id_tv_delete:
                if (mData.size() >= 1) {
                    mData.remove(mData.size() - 1);
                    mAdapter.notifyDataChanged();
                    mRecyclerViewAdapter.notifyDataChanged();
                    mRecyclerView.setDataSizes(mRecyclerViewAdapter.getCount());
                }
                break;
        }
    }

    @Override
    protected void onActive() {
        super.onActive();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackPressed() {
        terminateAbility();
        super.onBackPressed();
    }

    private class MyAdapter extends BaseItemProvider {
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
            MyHolder holder = null;
            String data = mData.get(position);
            if ((component == null) || (component.getTag() == null)) {
                component = LayoutScatter.getInstance(getContext())
                        .parse(ResourceTable.Layout_item_view_linear_ver, null, false);
                holder = new MyHolder(component);
                component.setTag(holder);
            } else {
                Object tag = component.getTag();
                if (tag instanceof MyHolder) {
                    holder = (MyHolder) tag;
                }
            }
            if (holder != null) {
                holder.mTvTxt.setText(data);
                if (position != 0) {
                    holder.mLine.setVisibility(Component.VISIBLE);
                } else {
                    holder.mLine.setVisibility(Component.HIDE);
                }
            }
            return component;
        }
    }

    private static class MyHolder {
        public        Text      mTvTxt;
        private final Component mLine;

        public MyHolder(Component component) {
            Component txt = component.findComponentById(ResourceTable.Id_tv_txt);
            if (txt instanceof Text) {
                mTvTxt = (Text) txt;
            }
            mLine = component.findComponentById(ResourceTable.Id_cp_line);
        }
    }
}
